package com.platform.car.app;


import com.platform.car.model.*;
import com.platform.car.service.*;
import com.platform.car.socket.SocketUtil;
import com.platform.common.log.SystemLog;
import com.platform.common.page.Page;
import com.platform.upms.model.UpmsPicture;
import com.platform.upms.model.json.Tip;
import com.platform.upms.service.UpmsPictureService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/*
 * 预约车位表管理 客户端 Controller
 * @author GaoXiang
 * @version 1.0
 */

@Controller
@RequestMapping("/car/app/parkuse")
public class AppParkuseController {


    /*
     * @param parkuse 携带userId、numberPlates、 停车场ID parkingId
     * @Description: 用户App下单预约车位
     * @Date:2017-11-14
     */
    @RequestMapping("/saveOrder")
    @ResponseBody
    public Tip saveOrder(Parkuse parkuse) {

//        String parkuseId = UUIDFactory.getStringId();
        Parking parking= parkingService.get(parkuse.getParkingId());
        try {
            //预约下单之前的必要判断
            if (!ValOrder(parkuse).getSuccess()){return ValOrder(parkuse);}
            //智能车位
            Parkinglot pl = new Parkinglot(parkuse.getParkingId(),"1","1");
            List<Parkinglot> parkinglots = parkinglotService.selectByParkingIdAndLock(pl);//智能地锁且空闲
            if(parkinglots.size()>0){
                Parkinglot parkinglot = saveHaveLock(parkinglots,parkuse,parking);
                return new Tip("预约成功！",parkinglot);
            }else {
                //非智能车位
                Parkinglot p = new Parkinglot(parkuse.getParkingId(),"1");
                List<Parkinglot> parkinglots1 = parkinglotService.selectByParkingIdAndLock(p);
                if(parkinglots1.size()>0){
                    Parkinglot parkinglot = saveNoLock(parkinglots1,parkuse,parking);
                    return new Tip("预约成功！",parkinglot);
                }else{
                    return new Tip(2,"此停车场没有空闲车位！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1, "预约错误！",e.getMessage());
        }
    }

     /*
     * 预约下单之前的必要判断
     * @param parkuse 实体对象
     * @return 提示信息
     */


    private Tip ValOrder(Parkuse parkuse){
        //根据车牌预约状态和用户判断此车辆是否预约
        if(parkuseService.countNumber(parkuse)>0){
            return new Tip(1,"您已预约！不能重复预约！");
        }
        //根据用户id、状态为4、车牌号、离开时间 判断某用户超时未处理的单子
        if(parkuseService.countNum(parkuse)>0){
            return new Tip(1,"您有超时未处理的订单，请完成订单后预约！");
        }
        return new Tip();
    }

     /*
     * 保存带地锁的空闲车位
     * @param parkinglotList 智能且空闲车位的集合
     * @param parkuse 实体对象
     * @param parking 实体对象
     * @param parkuseId id
     * @throws Exception 数据保存异常
     */

    private Parkinglot saveHaveLock(List<Parkinglot> parkinglotList,Parkuse parkuse,Parking parking) throws Exception{
            Parkinglot parkinglot = parkinglotList.get(0);//车位信息
            ParkingZone parkingZone=parkingZoneService.get(parkinglot.getZoneId());
            Integer imgId=parkingZone.getImgId();//获取停车场分区图片
            UpmsPicture upmsPicture=upmsPictureService.get(imgId);
            String parkingImg = upmsPicture.getPicUrl();//获取到停车场分区的图片
            parkinglot.setParkingImg(parkingImg);//停车位分区图片
            parkinglot.setSwitchStatus("0");//车位状态(预约的状态)
            //parkinglot.setParkuseId(parkuseId);
            parkinglot.setCharging(parking.getCharging());
            parkinglotService.updateById(parkinglot);
            if (parkinglot.getLockId() != null && !"".equals(parkinglot.getLockId())) {
                Lock lock = lockService.get(parkinglot.getLockId());
                if(lock!=null){
                  //  SocketUtil.socketTaskMap.get(lock.getNumber()).yuyue();
                    lock.setStatus("1");//地锁状态
                    lockService.update(lock);
                }
            }
            parkuse.setMakeTime(new Date());
            parkuse.setSetTime(new Date());//创建时间
            parkuse.setStatus("1");//已预约
            parkuse.setParkinglotId(parkinglot.getId());//车位id
            parkuseService.saveData(parkuse);
            return parkinglot;
    }

    /*
     * 保存不带地锁的空闲车位
     * @param parkinglots1 非智能且空闲车位的集合
     * @param parkuse 实体对象
     * @param parking 实体对象
     * @param parkuseId id
     * @return parkinglot 车位信息
     * @throws Exception 数据保存异常
     */

    private Parkinglot saveNoLock(List<Parkinglot> parkinglots1,Parkuse parkuse,Parking parking) throws Exception{
        Parkinglot parkinglot = parkinglots1.get(0);
        ParkingZone parkingZone=parkingZoneService.get(parkinglot.getZoneId());
        Integer imgId=parkingZone.getImgId();//获取停车场分区图片
        UpmsPicture upmsPicture=upmsPictureService.get(imgId);
        String parkingImg = upmsPicture.getPicUrl();//获取到停车场分区的图片
        System.out.println("-----------"+parkingImg);
        parkinglot.setParkingImg(parkingImg);//停车位分区图片
        parkinglot.setSwitchStatus("0");//车位状态
//        parkinglot.setParkuseId(parkuseId);//预约id
        parkinglot.setCharging(parking.getCharging());
        parkinglotService.updateById(parkinglot);
        parkuse.setMakeTime(new Date());//预约时间
        parkuse.setSetTime(new Date());//创建时间
        parkuse.setStatus("1");//已预约
        parkuse.setParkinglotId(parkinglot.getId());//车位id
        parkuseService.saveData(parkuse);
        return parkinglot;
    }



    /*
     * 2017年6月23日 10:00:26
     * 2017年5月31日  闫增宝  App用户撤销预约车位  传输id
     * @param parkuse
     * @return 成功失败
     */

    @RequestMapping("/revokeOrder")
    @ResponseBody
    public Tip revokeOrder(Parkuse parkuse) {
        Parkuse pu = parkuseService.selectOrder(parkuse);
        Parking parking = parkingService.get(parkinglotService.selectById(pu.getParkinglotId()).getParkingId());
        try {
            if (pu != null) {
                if (pu.getStatus().equals("2")) {//已使用状态
                    return new Tip(3, "车辆已进场不能取消订单!");
                } else if (pu.getStatus().equals("4")) {
                    if (pu.getParkinglotId() != null && !"".equals(pu.getParkinglotId())) {
                        parkinglotService.updateLotAndLock(pu);
                    }
                    pu.setStatus("3");//已离开
                    pu.setLeaveTime(new Date());
                    parkuseService.update(pu);

                    double[] expense = parkingpayService.computeMoney(pu,parking);//计算费用
                    Parkingpay parkingpay = new Parkingpay(pu.getId(),Integer.valueOf((int)expense[0]),Integer.valueOf((int)expense[1]),expense[2],"0");
                    parkingpayService.saveData(parkingpay);
                    return new Tip("取消成功，已生成订单！",parkingpay);
                }else if (pu.getStatus().equals("1")){
                    if (pu.getParkinglotId() != null && !"".equals(pu.getParkinglotId())) {
                        parkinglotService.updateLotAndLock(pu);
                    }
                    parkuseService.deleteDataById(pu);
                    return new Tip("取消成功！");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return new Tip(1, "取消出现异常！",e.getMessage());
        }
        return new Tip(1,"无效订单！数据库没有此数据！");
    }

    /**
     *  2017年6月6日 姜延鹏
     * 预约详情，停车场信息，车位剩余信息，计费信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/parkuseDetail")
    @ResponseBody
    public Tip parkuseDetail(String id){
        //预约详情，停车场信息
        Parkuse parkuseDetail = parkuseService.parkuseDetail(id);//根据id查询

        //车位剩余信息
        Parking parking = new Parking();
        parking.setId(parkuseDetail.getParkingId());
        Long countParkTotal = parkingService.countParkTotal(parking);
        Long countPark = parkingService.countPark(parking);
        Long countAutoParkTotal = parkingService.countAutoParkTotal(parking);
        Long countAutoPark = parkingService.countAutoPark(parking);
        Long countOrdinaryParkTotal = parkingService.countOrdinaryParkTotal(parking);
        Long countOrdinaryPark = parkingService.countOrdinaryPark(parking);
        parkuseDetail.setCountParkTotal(countParkTotal);
        parkuseDetail.setCountPark(countPark);
        parkuseDetail.setCountAutoParkTotal(countAutoParkTotal);
        parkuseDetail.setCountAutoPark(countAutoPark);
        parkuseDetail.setCountOrdinaryParkTotal(countOrdinaryParkTotal);
        parkuseDetail.setCountOrdinaryPark(countOrdinaryPark);
        Date now = new Date();
        parkuseDetail.setCountdown(now);
        Lock lock = lockService.get(parkuseDetail.getLockId());
        parkuseDetail.setLock(lock);


        //计费信息，当前价格（正在停车的）、价格（已完成的）
        if (parkuseDetail.getStatus().equals("1")){
            //当前费用
            parkuseDetail.setPayfee(0.0);
            //总费用
            parkuseDetail.setTotalPay(0.0);
        }else {
            Date one=parkuseDetail.getUseTime();//进来时间
            Date two= new Date();//出去时间
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff =time2 - time1;
            long  hour = (diff / (60 * 60 * 1000));//小时数
            long  min = ((diff / (60 * 1000)) - hour * 60);//分数
            long  sec = (diff/1000 -hour*60*60-min*60);//秒数
            if(min>0||sec>0){
                hour =hour+1;
            }
            Double  day = Math.floor(hour/24)  ;//天数
            long yu= hour%24;//余下的小时数
            Double light =0.0;//白天时长
            Double night =0.0;//晚上时长
            if(day>0){
                light =  Double.valueOf(String.valueOf(day*12));
                night=  Double.valueOf(String.valueOf(day*12));
            }
            if(yu>0){
                Calendar rightNow = Calendar.getInstance();
                rightNow.setTime(one);
                int h = rightNow.get(Calendar.HOUR_OF_DAY);
                //long h= one.getHours();  //获取停车时间的小时是几点
                long hyu=yu+h;     //停车时间的小时数  加上余下的小时数
                if(h>=6&&hyu<=24){ //6点及6点后停车，24点之前取车
                    light=light+ Double.valueOf(String.valueOf(yu));
                }else if(h<6&&hyu<=24&&hyu>6){ //6点前停车，6点之后，24点之前取车
                    night= night+ Double.valueOf(String.valueOf(6-h));
                    light=light+ Double.valueOf(String.valueOf(hyu-6));
                }else if(h<6&&hyu<=6){//6点前停车，6点前取车
                    night= night+ Double.valueOf(String.valueOf(yu));
                }else if(h>=6&&hyu>24){//6点及6点后停车，24点之后取车
                    if(hyu-24>=6){
                        night= night+6;
                        light=light+ Double.valueOf(String.valueOf(yu-6));
                    }else{
                        night= night+ Double.valueOf(String.valueOf(hyu-24));
                        light=light+ Double.valueOf(String.valueOf(24-h));
                    }
                }else if(h<6&&hyu>24){//6点前停车，24点之后取车
                    night= night+ Double.valueOf(String.valueOf(yu-18));
                    light=light+ Double.valueOf(String.valueOf(42-hyu));
                }
            }
            Double dayFee = parkuseDetail.getDayFee();//停车场白天费用
            Double nightFee = parkuseDetail.getNightFee();//停车场夜晚费用
            //计算费用
            Double dayFees = dayFee*light;
            Double nightFees = nightFee*night;
            //当前费用
            parkuseDetail.setPayfee(dayFees+nightFees);
            if (parkuseDetail.getStatus().equals("3")){
                //总费用
                parkuseDetail.setTotalPay(dayFees+nightFees);
            }else {
                parkuseDetail.setTotalPay(0.0);
            }
        }
        return new Tip(parkuseDetail);
    }


    /*
     * 2017年6月22日  闫增宝  增加计算实时费用
     * 预约时间、预约状态、车牌号、实际开始时间、实际离开时间、停车场信息、停车位信息、地锁信息
     * 支付列表  白天时长 夜晚时长 费用 支付状态
     * @param parkuse userId  或者传输 用户id和车牌号
     * @return parkuseList
    */
    @RequestMapping(value = "/selectForList")
    @ResponseBody
    public Tip selectForList(Parkuse parkuse,Integer page,Integer size,Page<Parkuse> parkusePage){
        parkusePage.setPageNum(page);
        parkusePage.setPageSize(size);
        //根据accountId查询
        parkusePage = parkuseService.findByPage(parkusePage,parkuse);

        if(parkusePage.getResults().size()>0){
            for (Parkuse parkuse1:parkusePage.getResults()) {
                Parking parking = new Parking();
                Parkinglot parkinglot = parkinglotService.selectById(parkuse1.getParkinglotId());
                //停车位信息
                parkuse1.setParkinglot(parkinglot);
                if (parkinglot !=null){
                    parking = parkingService.get(parkinglot.getParkingId());
                    parkuse1.setParking(parking);//停车场信息
                    //当前停车的实时费用
                    if(parkuse1.getStatus().equals("2")){
                        Double payFee = CountPayFee(parkuse1,parking);
                        //当前费用（实时费用）
                        parkuse1.setPayfee(payFee);
                    }else if(parkuse1.getStatus().equals("4")){
                        Double payFee = CountPayFee(parkuse1,parking);
                        parkuse1.setPayfee(payFee);
                    }
                    if (parkinglot.getLockId()!=null &&!"".equals(parkinglot.getLockId())){
                        Lock lock = lockService.get(parkinglot.getLockId());
                        parkuse1.setLock(lock);//地锁信息
                    }
                }
                //支付信息（总费用）
                parkuse1.setParkingpays(parkingpayService.selectByParkuserId(parkuse1.getId()));
            }
        }else{
            return new Tip(1,"没有预约记录！", parkusePage);
        }
        return new Tip(parkusePage);
    }

    /**
     * 计算实时费用
     * @param parkuse
     * @param parking
     * @return
     */
    public double CountPayFee(Parkuse parkuse,Parking parking){
        Date one = parkuse.getUseTime();//进来时间
        Date two = new Date();//假设出去时间
        long time1 = one.getTime();
        long time2 = two.getTime();
        long diff = time2 - time1;
        long hour = (diff / (60 * 60 * 1000));//小时数
        long min = ((diff / (60 * 1000)) - hour * 60);//分数
        long sec = (diff / 1000 - hour * 60 * 60 - min * 60);//秒数
        if(min>0||sec>0){
            hour =hour+1;
        }
        Double  day = Math.floor(hour/24)  ;//天数
        long yu= hour%24;//余下的小时数
        Double light =0.0;//白天时长
        Double night =0.0;//晚上时长
        if(day>0){
            light =  Double.valueOf(String.valueOf(day*12));
            night=  Double.valueOf(String.valueOf(day*12));
        }
        if(yu>0){
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(one);
            int h = rightNow.get(Calendar.HOUR_OF_DAY);
            long hyu=yu+h;     //停车时间的小时数  加上余下的小时数
            if(h>=6&&hyu<=24){ //6点及6点后停车，24点之前取车
                light=light+ Double.valueOf(String.valueOf(yu));
            }else if(h<6&&hyu<=24&&hyu>6){ //6点前停车，6点之后，24点之前取车
                night= night+ Double.valueOf(String.valueOf(6-h));
                light=light+ Double.valueOf(String.valueOf(hyu-6));
            }else if(h<6&&hyu<=6){//6点前停车，6点前取车
                night= night+ Double.valueOf(String.valueOf(yu));
            }else if(h>=6&&hyu>24){//6点及6点后停车，24点之后取车
                if(hyu-24>=6){
                    night= night+6;
                    light=light+ Double.valueOf(String.valueOf(yu-6));
                }else{
                    night= night+ Double.valueOf(String.valueOf(hyu-24));
                    light=light+ Double.valueOf(String.valueOf(24-h));
                }
            }else if(h<6&&hyu>24){//6点前停车，24点之后取车
                night= night+ Double.valueOf(String.valueOf(yu-18));
                light=light+ Double.valueOf(String.valueOf(42-hyu));
            }
        }
        Double dayFee = parking.getNightFee();//停车场白天费用
        Double nightFee = parking.getNightFee();//停车场夜晚费用
        //计算费用
        Double dayFees = dayFee*light;
        Double nightFees = nightFee*night;
        Double payFee = dayFees+nightFees;
        return payFee;
    }




    /**
     * 根据车牌号查询是否预约
     * @param plates
     * @return
     */
    @RequestMapping(value = "/isParkuse")
    @ResponseBody
    public  Tip  isParkuse(String plates){
        Parkuse p=new Parkuse(plates);
        List<Parkuse> parkuses = parkuseService.selectByPlate(p);
        if(parkuses.size()>0){
            return  new Tip(2,"1:已预约");
        }else{
            return  new Tip(2,"0:未预约");
        }
    }


    /*
     * 2017年5月26日 闫增宝
     * 进入停车场 实际停车时间开始、 状态修改
     *
     * @param parkuse 携带车牌号码
     * @return 成功失败
     */

    @RequestMapping("/updateStart")
    @ResponseBody
    public Tip updateStart(Parkuse parkuse) {
        Tip tip = new Tip();
        try {
            parkuse.setStatus("1");
            Parkuse pu = parkuseService.selectByCpAndStatus(parkuse);
            if (pu != null) {
                pu.setUseTime(new Date());
                pu.setStatus("2");//已使用
                parkuseService.update(pu);

                Parkinglot parkinglot = parkinglotService.selectById(pu.getParkinglotId());
                if (parkinglot != null) {
                    parkinglot.setSwitchStatus("2");//车位状态  已使用
                    parkinglotService.updateById(parkinglot);
                }
                tip.setSuccess(true);
                tip.setData("保存成功！");
            } else {
                tip.setSuccess(false);
                tip.setData("未查到相关数据！保存失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1, "出现异常！保存失败！");
        }
        return tip;
    }

    /*
     * 2017年5月26日 闫增宝
     * 进入停车场 实际离开时间开始、 状态修改
     * @param parkuse 携带车牌号码
     * @return 成功失败
     */

    @RequestMapping("/updateEnd")
    @ResponseBody
    public Tip updateEnd(Parkuse parkuse) {
        Tip tip = new Tip();
        try {
            parkuse.setStatus("2");
            Parkuse pu = parkuseService.selectByCpAndStatus(parkuse);
            if (pu != null) {
                pu.setLeaveTime(new Date());
                pu.setStatus("3");//已离开
                parkuseService.update(pu);

                Parkinglot parkinglot = parkinglotService.selectById(pu.getParkinglotId());
                if (parkinglot != null) {
                    parkinglot.setSwitchStatus("3");//车位状态  未使用
                    parkinglotService.updateById(parkinglot);
                }
                tip.setSuccess(true);
                tip.setData("保存成功！");
            } else {
                tip.setSuccess(false);
                tip.setData("未查到相关数据！保存失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(1, "出现异常！保存失败！");
        }
        return tip;
    }


    //---------------------------- property -------------------------------

    @Resource
    private ParkuseService parkuseService;

    @Resource
    private ParkinglotService parkinglotService;

    @Resource
    private LockService lockService;

    @Resource
    private ParkingService parkingService;

    @Resource
    private ParkingpayService parkingpayService;

    @Resource
    private CaptureService captureService;

    @Resource
    private ParkingZoneService parkingZoneService;

    @Resource
    private UpmsPictureService upmsPictureService;

}
